<template>
  <div class="main">
    <section class="sign-in-container">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm">
        <div class="item">
          <div class="title">基础信息</div>
          <el-form-item label="活动标题:" prop="name">
            <el-input v-model="ruleForm.name" :disabled="disabled||editDisabled" maxlength="30" clearable placeholder="活动标题不超过30个字符"></el-input>
          </el-form-item>
          <el-form-item label="活动时间:" prop="startTime">
            <div class="block">
              <el-date-picker v-model="ruleForm.startTime" :disabled="disabled||editDisabled" type="date" placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="活动头部图:" prop="coverImgs">
            <div class="activeHeadImg">
              <el-upload class="" accept="image/*" :disabled="disabled||editDisabled" :action="upladUrl" name="file"
                :show-file-list="false" :on-success="uploadSuccess" :before-upload="beforeUpload">
                <img v-if="ruleForm.coverImgs" :src="ruleForm.coverImgs" style="width: 100px;" class="awardImg" />
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <span class="advice">建议图片宽度为750 高度不限制</span>
            </div>
          </el-form-item>
          <el-form-item label="活动背景色:" prop="backColor">
            <div class="activeBackground">
              <colorPicker v-model="ruleForm.backColor" :disabled="disabled||editDisabled" @change="handleChangeColor"></colorPicker>
              &nbsp;&nbsp;&nbsp;<span>选择颜色</span>
            </div>
          </el-form-item>
        </div>
        <div class="item">
          <div class="title">活动规则</div>
          <el-form-item label="等级限制:" prop="limitMemberList">
            <el-checkbox-group v-model="ruleForm.limitMemberList" :disabled="disabled||editDisabled">
              <el-checkbox label="0" class="check-box">普通</el-checkbox>
              <el-checkbox label="1" class="check-box">VIP</el-checkbox>
              <el-checkbox label="2" class="check-box">钻石</el-checkbox>
              <el-checkbox label="3" class="check-box">董事</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="领取规则:" prop="ruleList">
            <div class="rule-list" v-for="(item,index) in ruleForm.ruleList" :key="index">
              <div>
                <div class="title">
                  规则{{index+1}}
                  <span class="detail-rule" v-if="!(disabled||editDisabled)" @click="detailRule(item,index)">移除规则</span>
                </div>
              </div>
              <div class="filter-container">
                <div class="title" style="margin-right:10px;">领取时间:</div>
                <el-form-item :prop="'ruleList.'+index+'.startTime'" :rules="prizeListRule.time">
                  <el-time-picker v-model="item.startTime" :disabled="disabled||editDisabled" @change="dateChange(index)"
                    format="HH:mm" value-format="HH:mm" placeholder="开始时间" :picker-options="{
                      selectableRange: '00:00:00 - 23:59:00'
                    }">
                  </el-time-picker>
                </el-form-item>
                <span style="margin: 0px 10px;"> 至 </span>
                <el-form-item :prop="'ruleList.'+index+'.endTime'" :rules="prizeListRule.time">
                  <el-time-picker v-model="item.endTime" :disabled="disabled||editDisabled" format="HH:mm" value-format="HH:mm"
                    placeholder="结束时间" :picker-options="{
                      selectableRange:`${item.startTime ? item.startTime +':00' : '00:00:00'}-23:59:00`
                    }">
                  </el-time-picker>
                </el-form-item>
              </div>
              <el-form-item :prop="'ruleList.'+index+'.ruleGoodsList'" :rules="prizeListRule.ruleGoodsList">
                <div class="title" style="margin: -5px 10px 0px 0px;">领取商品:</div>
                <div class="filter-container" style="margin-top: 5px;margin-bottom: -2px;">
                  <el-button type="primary" :disabled="disabled" icon="el-icon-plus" class="filter-item"
                    @click="addGoods(item,index)" size="mini">添加商品</el-button>
                </div>
                <el-table :data="item.ruleGoodsList" style="border: 1px solid #EEEEEE;" ref="downTable">
                  <!-- 外层下拉 -->
                  <el-table-column align="center" type="expand" width="80">
                    <!-- 嵌套的类型 -->
                    <template slot-scope="scope" v-if="scope.row.goodsList">
                      <el-table :data="scope.row.goodsList" highlight-current-row border ref="table2">
                        <el-table-column align="center" label="图库" width="110" fixed>
                          <template slot-scope="$scope">
                            <img :src="$scope.row.skuImage" alt="" class="avatar-img">
                          </template>
                        </el-table-column>
                        <el-table-column align="center" label="款号" min-width="70px">
                          <template slot-scope="$scope">
                            <span>{{$scope.row.serialNo}}</span>
                          </template>
                        </el-table-column>
                        <!-- <el-table-column
                          v-for="(attr, k) in getAttr(scope.row.goodsList[scope.$index])" :key="k"
                          align="center" :label="'属性值'+(k+1)"
                          min-width="100px">
                          <template slot-scope="$scope">
                            <span>{{attr}}</span>
                          </template>
                        </el-table-column> -->
                        <el-table-column v-for="(attr, k) in attrList" :key="k"
                          v-if="scope.row.goodsList[0][attr.id]&&scope.row.goodsType==1" align="center" :label="'规格'"
                          :prop="attr.prop" min-width="100px">
                        </el-table-column>
                        <el-table-column align="center" label="市场价" min-width="70px">
                          <template slot-scope="$scope">
                            <span>{{$scope.row.marketValue||0}}</span>
                          </template>
                        </el-table-column>
                        <el-table-column align="center" label="销售价" min-width="70px">
                          <template slot-scope="$scope">
                            <span>{{$scope.row.price||0}}</span>
                          </template>
                        </el-table-column>
                        <el-table-column align="center" label="VIP价" min-width="70px">
                          <template slot-scope="$scope">
                            <span>{{$scope.row.regionPrice||0}}</span>
                          </template>
                        </el-table-column>
                        <el-table-column align="center" label="钻石价" min-width="70px">
                          <template slot-scope="$scope">
                            <span>{{$scope.row.diamondPrice||0}}</span>
                          </template>
                        </el-table-column>
                        <el-table-column align="center" label="董事价" min-width="70px">
                          <template slot-scope="$scope">
                            <span>{{$scope.row.directorPrice||0}}</span>
                          </template>
                        </el-table-column>
                        <el-table-column align="center" label="库存数" prop="stockNum" min-width="86px"
                          v-if="scope.row.goodsType==1">
                          <template slot-scope="$scope">
                            <span v-if="$scope.row.stockNum">{{$scope.row.stockNum}}</span>
                            <span v-else style="color: red">库存不足</span>
                          </template>
                        </el-table-column>
                        <el-table-column v-if="!disabled" align="center" label="操作" width="80" fixed="right">
                          <template slot-scope="$scope">
                            <a class="remove" @click="delGoodsItem(item, scope.$index)" href="#">移除</a>
                          </template>
                        </el-table-column>
                      </el-table>
                    </template>
                  </el-table-column>
                  <el-table-column align="left" label="类型" width="140">
                    <template slot-scope="scope">
                      <span v-if="scope.row.goodsType==1">商品</span>
                      <span v-if="scope.row.goodsType==2">套餐</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="left" label="名称">
                    <template slot-scope="scope">
                      <span style="color: #409eff">
                        {{scope.row.title}}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="!disabled" align="center" label="操作" width="120">
                    <template slot-scope="scope">
                      <a href="javascript: void(0);" class="el-icon-remove"
                        @click="delGoodsItem(item, scope.$index)"></a>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </div>
            <div v-if="!(disabled||editDisabled)" class="title"><span class="add-rule" @click="addRule">新增规则</span></div>
          </el-form-item>
          <el-form-item label="同款商品限购数量:" prop="limitOrderNumber">
            <div>
              最多可购
              <el-input type="number" :disabled="disabled||editDisabled" placeholder="最多可购" v-model="ruleForm.limitOrderNumber"
                style="width: 100px;">
              </el-input>
              件
            </div>
          </el-form-item>
          <el-form-item label="是否开启:" prop="status">
            <el-switch v-model="ruleForm.status" :disabled="disabled" active-color="#13ce66" inactive-color="#ff4949"
              :active-value="1" :inactive-value="0">
            </el-switch>
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" :disabled="disabled" @click="save()">保存</el-button>
        </el-form-item>
      </el-form>
    </section>
  </div>
</template>

<script>
  import {
    formatDate,
    isEmpty,
    isNull,
    regexp,
    debounce
  } from '@/utils/tools'
  import differenceBy from 'lodash/differenceBy';
  import {
    freeCollection
  } from '@/api/activity/freeCollection'
  import Vue from 'vue'
  import vcolorpicker from 'vcolorpicker'
  Vue.use(vcolorpicker)
  export default {
    components: {
    },
    data() {
      //计算时间不能超过上个活动
      var time = (rule, value, callback) => {
        if (!value) {
          callback('领取时间不能为空!');
        } else {
          callback();
        }
      };
      var limitOrderNumber = (rule, value, callback) => {
        if (value<0) {
          callback('不能小于0!');
        } else {
          callback();
        }
      };
      return {
        //属性列表
        attrList: [{
            id: 'attrId',
            prop: 'attrValue'
          },
          {
            id: 'attrId1',
            prop: 'attrValue1'
          },
          {
            id: 'attrId2',
            prop: 'attrValue2'
          },
          {
            id: 'attrId3',
            prop: 'attrValue3'
          },
          {
            id: 'attrId4',
            prop: 'attrValue4'
          },
          {
            id: 'attrId5',
            prop: 'attrValue5'
          },
          {
            id: 'attrId6',
            prop: 'attrValue6'
          }
        ],
        ruleForm: {
          backColor: "", //背景色
          coverImgs: "", //图片
          id: 1,
          name: "", //活动标题
          //规则
          ruleList: [],
          length: 2,
          startTime: "", //活动时间
          status: 1,
          type: 30,
          limitMemberList:[]
        },
        disabled: false,
        timeIndex: 0, //时间下标
        prizeListRule: {
          prizeType: [{
            required: true,
            message: '请输入奖品类型',
            trigger: 'blur'
          }, ],
          ruleGoodsList: [{
            required: true,
            message: '请添加商品',
            trigger: 'blur'
          }, ],
          time: [{
            validator: time,
            trigger: 'blur'
          }],
        },
        rules: {
          name: [{
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          }, ],
          startTime: [{
            required: true,
            message: '请选择时间',
            trigger: 'blur'
          }, ],
          coverImgs: [{
            required: true,
            message: '请上传图片',
            trigger: 'blur'
          }, ],
          backColor: [{
            required: true,
            message: '请选择颜色',
            trigger: 'blur'
          }, ],
          ruleList: [{
            required: true,
            message: '请添加规则',
            trigger: 'blur'
          }, ],
          limitOrderNumber: [{
            required: true,
            message: '请输入限购数量',
            trigger: 'blur'
          }, {
            validator: limitOrderNumber,
            trigger: 'blur'
          }],
          limitMemberList: [{
            required: true,
            message: '请选择等级限制',
            trigger: 'blur'
          }],
        },
        pageType: '', //类型
        discountId: '',
        expends: [],
        editDisabled:false,//活动状态=活动中时设为true，仅可对活动商品进行移除、添加操作
      };
    },
    watch: {
      'ruleForm.ruleList': {
        handler(val, oldVal) {
          function compareDate(t1, t2) {
            var date = new Date();
            var a = t1.split(":");
            var b = t2.split(":");
            return date.setHours(a[0], a[1]) > date.setHours(b[0], b[1]);
          }
          debounce(()=>{
            if (this.timeIndex > 0) {
              if (compareDate(this.ruleForm.ruleList[this.timeIndex - 1].endTime, this.ruleForm.ruleList[this.timeIndex]
                  .startTime || '')) {
                this.ruleForm.ruleList[this.timeIndex].startTime = ''
                this.$message.error('活动开始时间不能小于上次活动结束时间');
              }
            }
          },600)();
        },
        deep: true //true 深度监听
      }
    },
    mounted() {
      //获取详情数据
      this.pageType = this.$route.query.type
      this.discountId = this.$route.query.discountId
      if (this.pageType == 'edit' || this.pageType == 'see') {
        if (this.pageType == 'see') {
          this.$nextTick(_ => {
            this.$store.dispatch('editTageTitle', {
              name: "freeCollectionAdd",
              title: "查看"
            })
          });
          this.disabled = true
        } else {
          this.$nextTick(_ => {
            this.$store.dispatch('editTageTitle', {
              name: "freeCollectionAdd",
              title: "编辑"
            })
          });
        }
        this.getData()
      } else {
        this.$nextTick(_ => {
          this.$store.dispatch('editTageTitle', {
            name: "freeCollectionAdd",
            title: "新增"
          })
        });
      }
    },
    methods: {
      dateChange(index) {
        this.timeIndex = index
      },
      removeShop(index) {
        console.log(index)
        console.log(this.ruleForm)
        this.ruleForm.ruleList[0].ruleGoodsList[index].goodsList = this.ruleForm.ruleList[0].ruleGoodsList[index]
          .goodsList.splice(index + 1, 1)
        console.log(this.ruleForm.ruleList)
      },
      getAttr(obj) {
        let arr = [];
        Object.keys(obj).filter((key) => key.includes('attrValue')).forEach((key) => {
          arr.push(obj[key]);
        });
        return arr;
      },
      //新增规则
      addRule() {
        this.ruleForm.ruleList.push({
          endTime: "",
          ruleGoodsList: [],
          startTime: "",
        });
      },
      //删除规则
      detailRule(item, index) {
        this.ruleForm.ruleList.splice(index, 1);
      },
      //添加商品
      addGoods(item, index) {
        console.log(item);
        if (!item.ruleGoodsList) {
          this.$set(item, 'ruleGoodsList', []);
        }
        // let goods= item.ruleGoodsList.filter(a => a.goodsType === 1).map(i => {
        //   return {
        //     goodsId: i.goodsId,
        //     name: i.title
        //   }
        // });
        this.goodsChoose({count:1}, [])
        .then(val => {
          let goodsIds=val.map(x => {
            return x.goodsId
          });
          //检查商品是否参加过活动
          freeCollection.freeCheapCheck({
            goodsIds: goodsIds,
            goodsType:1,//商品：1，套餐：2
            discountType:30,//区分免费低价购,30免费领,31低价购
          }).then(res=>{
            if(res.data.haveJoin){
              let activityType={groupBuy:'拼团活动',full:'满减活动',crush:'秒杀活动',free:'免费领',cheap:'低价购'}
              this.$message.error(`该商品已参加${activityType[res.data.activityType]}`);
              return;
            }
            //sku选择
            let goods = val[0];
            console.log(goods);
            if (item.ruleGoodsList.findIndex(x => x.goodsId === goods.goodsId) !== -1) {
              this.$message.error('该规则下商品已存在')
              return false
            } else {
              let newGood = {
                goodsId: goods.goodsId,
                goodsList: [],
                goodsType: 1,
                title: goods.name
              }
              this.$skuSelect({
                id: goods.id,
                multiple: false
              }).then(res2 => {
                console.log(res2);
                let skuList = res2;
                if (!Array.isArray(skuList)) {
                  skuList = [skuList];
                }
                skuList.map(x => {
                  x.stockNum = x.totalSkuNumber;//库存数
                  x.price=0;//销售价置0
                  x.regionPrice=0;//VIP价置0
                  x.diamondPrice=0;//钻石价置0
                  x.directorPrice=0;//董事价置0
                })
                newGood.goodsList = skuList;
                item.ruleGoodsList.push(newGood);
              })
            }
          });
        })
        .catch(err => {
          // this.tempGoodsDetail = {}
        })
      },
      //删除商品
      delGoodsItem(item, $index) {
        item.ruleGoodsList.splice($index, 1);
      },
      getData() {
        freeCollection.freeCheapDetail({
          discountId: this.discountId
        }).then(res => {
          if (res.status == 200) {
            this.ruleForm = res.data || {};
            let limitMemberList=this.ruleForm.limitMemberCardType.split(',');//等级限制拆分
            let a=limitMemberList.findIndex(x=>x=='-1');
            if(a!=-1){
              limitMemberList=limitMemberList.splice(a,1);//删除-1
            }
            console.log(limitMemberList);
            this.$set(this.ruleForm,'limitMemberList',limitMemberList);
            if(res.data.activityStatusCode==='going'){
              this.editDisabled=true;
            }else if(res.data.activityStatusCode==='end'||res.data.activityStatusCode==='expire'){
              this.disabled=true;
            }
          }
        })
      },
      handleChangeColor(val) {
        console.log('输出颜色值', val) // 颜色 #6c8198
      },
      beforeUpload(file) {
        if (!/image/.test(file.type)) {
          this.$message.error('只能上传图片')
          return false
        }
        if (file.size > 1024 * 1024) {
          this.$message.error('图片不能大于1M')
          return false
        }
      },
      uploadSuccess(res) {
        this.ruleForm.coverImgs = this.replaceImgUrl(res.filePath)
        console.log(this.ruleForm.coverImgs)
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      //保存
      async save() {
        this.$refs.ruleForm.validate(valid => {
          if (!valid) {
            return false;
          }
          // for (let a of this.ruleForm.ruleList) {
          //   for (let b of a.ruleGoodsList) {
          //     for (let c of b.goodsList) {
          //       if (isNull(c.price) || isNull(c.maximumCommission)) {
          //         this.$message.warning('存在价格或佣金为空的商品/套餐');
          //         return;
          //       }
          //       if (!regexp.money.test(c.price)) {
          //         this.$message.warning('商品/套餐价格须大于0,小于1000000且最多保留两位小数');
          //         return;
          //       }
          //       if (!regexp.zMoney.test(c.maximumCommission)) {
          //         this.$message.warning('商品/套餐佣金须大于等于0,小于100000000且最多保留两位小数');
          //         return;
          //       }
          //     }
          //   }
          // }
          let data = JSON.parse(JSON.stringify(this.ruleForm));
          data.freeRuleList = [];
          for (let a of data.ruleList) {
            for (let b of a.ruleGoodsList) {
              b.startTime = a.startTime;
              b.endTime = a.endTime;
              b.ruleGoodsList = b.goodsList;
              delete b.goodsList;
              data.freeRuleList.push(b);
            }
          }
          data.type = 30; //免费领
          data.limitMemberCardType=data.limitMemberList.join(',');//等级限制添加逗号
          console.log(data);
          if(this.pageType == 'edit'){
            freeCollection.freeCheapEdit(data).then(res=>{
              this.$message.success('编辑成功');
              setTimeout(_=>{
                this.$router.go(-1);
              },1000)
            })
          }else{
            freeCollection.freeCheapAdd(data).then(res=>{
              this.$message.success('新增成功');
              setTimeout(_=>{
                this.$router.go(-1);
              },1000)
            })
          }
        });
      }
    }
  }
</script>

<style lang="scss" scoped="scoped">
  .remove {
    color: #027DB4;
  }

  .to {
    padding: 0 10px;
  }

  .receiveTime {
    .el-date-editor {
      width: 100px;
    }
  }

  .activeBackground {
    display: flex;
    align-items: center;

    .m-colorPicker {
      border: 1px solid #EEEEEE;
      display: inline-block;

      /deep/ .colorBtn {
        width: 20px;
        height: 20px;
      }
    }
  }

  .avatar-uploader-icon {
    width: 100px;
    height: 100px;
    border: 1px solid #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 10px;
  }

  .activeHeadImg {
    display: flex;
    align-items: flex-end;
  }

  .main>section {
    padding: 12px;
  }

  .item>.title {
    background-color: #F2F2F2;
    height: 40px;
    display: flex;
    align-items: center;
    text-indent: 20px;
    margin-bottom: 40px;
  }

  /deep/ {
    .el-form-item.is-error .el-input__inner,
    .el-form-item.is-error .el-input__inner:focus,
    .el-form-item.is-error .el-textarea__inner,
    .el-form-item.is-error .el-textarea__inner:focus,
    .el-message-box__input input.invalid,
    .el-message-box__input input.invalid:focus {
      border-color: #F56C6C !important;
    }
  }

  .prizeName {
    padding-right: 10px;
  }

  .award {
    display: flex;

    .prizeItem {
      flex: 2;
      display: flex;
    }

    .imgItem {
      flex: 1;
    }

    .nameItem,
    .probabilityItem,
    .sortItem {
      flex: 2;
    }
  }

  .uploadImg {
    padding: 0 5px;
  }

  .prizeModel {
    height: 62px;
    width: 30px;
  }

  .el-checkbox {
    margin: 10px 0;
  }

  .yhq {
    width: 150px;
    vertical-align: middle;
    display: inline-block;
    display: flex;
    align-items: center;
    padding: 0 5px;

    span:nth-child(1) {
      border-left: 1px solid #ccc;
      border-top: 1px solid #ccc;
      border-bottom: 1px solid #ccc;
      border-top-left-radius: 5px;
      border-bottom-left-radius: 5px;
      padding: 0 5px;
    }

    span:nth-child(2) {
      border: 1px solid #ccc;
      border-top-right-radius: 5px;
      border-bottom-right-radius: 5px;
    }
  }

  .image {
    width: 43px;
    height: 38px
  }

  .inlineBlock {
    display: flex;
    flex-direction: row;
  }

  /deep/.inlineBlock {
    .el-upload {
      border: 1px solid #ccc;
      width: 43px;
    }
  }

  .lottery_item {
    margin-bottom: 20px;
  }

  /deep/.avatar-uploader {
    width: 43px;
    height: 43px;
    display: inline-block;
    vertical-align: middle;

    .el-upload {
      width: 100% !important;
      height: 100% !important;
    }
  }

  .get_condition {
    display: flex;
    flex-direction: column;
    transform: translateY(-20px);
    width: 80%;
  }

  .active_time {
    display: flex;
  }

  .date_group {
    display: flex;

    .line {
      padding: 0 10px;
    }
  }

  .awardImg {
    width: 100px;
    height: 100px;
    position: absolute;
    top: 0;
    left: 0;
  }

  /deep/.time {
    width: 200px;

    .el-input {
      width: 100% !important;
    }
  }

  /* 通用样式 */
  .smallInput {
    width: 150px;
    padding: 5px 10px;
  }

  .main {
    padding-top: 20px;
  }

  .rule-list {
    margin-bottom: 20px;

    .filter-container {
      display: flex;
      align-items: center;
    }

    .avatar-img {
      width: 80px;
      height: 80px;
      display: block;
      margin: auto;
    }

    .detail-rule {
      cursor: pointer;
      color: #ff4949;
      margin-left: 15px;
    }
  }

  .add-rule {
    color: #409EFF;
    cursor: pointer;
  }
  .check-box{
    margin-right: 20px;
    margin-top: 0px;
  }

  .m-colorPicker /deep/.box.open{
    visibility: visible;
    opacity: 1;
    z-index: 100;
  }

</style>
